package com.jxau.service.impl;

import Jama.EigenvalueDecomposition;
import Jama.Matrix;
import com.jxau.exception.Error;
import com.jxau.service.AlgorithmService;
import com.jxau.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lts
 * @create 2022-04-30 21:13
 */
@Service
public class AlgorithmServiceImpl implements AlgorithmService {
    @Override
    public Matrix addMatrix(String str1, String str2) {
        List<Matrix> matrixs = StringUtils.createMatrix(str1, str2);
//                创建两个矩阵对象，用于进行矩阵相加
        Matrix matrix1 = matrixs.get(0);
        Matrix matrix2 = matrixs.get(1);
        Matrix result = null;
//        矩阵相加
        try{
            result = matrix1.plus(matrix2);
        }catch (Exception e){
        }
        return result;
    }

    @Override
    public Matrix multipMatrix(String str1, String str2) {

        List<Matrix> matrixs = StringUtils.createMatrix(str1, str2);
//                创建两个矩阵对象，用于进行矩阵相乘
        Matrix matrix1 = matrixs.get(0);
        Matrix matrix2 = matrixs.get(1);

        Matrix result = null;
        try {
//          矩阵相乘
            result = matrix1.times(matrix2);
        }catch (Exception e){}
        return result;
    }

    //矩阵转置
    @Override
    public Matrix transposeMatrix(String str1) {
        Matrix matrix = StringUtils.createMatrix(str1);
        Matrix result = null;
        try {
            result = matrix.transpose();
        }catch (Exception e){}
        return result;
    }

    //逆矩阵
    @Override
    public Matrix inverseMatrix(String str1) {
        Matrix matrix = StringUtils.createMatrix(str1);
        Matrix result = null;
        try{
            result = matrix.inverse();
        }catch (Exception e){}
        return result;
    }

    @Override
    public Integer rankMatrix(String str1) {
        Matrix matrix = StringUtils.createMatrix(str1);
        int result = -1;
        try{
            result = matrix.rank();
        }catch (Exception e){}
        return result;
    }

    //求矩阵特征值
    @Override
    public Set eigMatrix(String str1) {
        Matrix matrix = StringUtils.createMatrix(str1);
        Set set = new HashSet();
        try{
            //        获取这个对象，调用方法获取特征值
            EigenvalueDecomposition result = matrix.eig();
            double[] realEigenvalues = result.getRealEigenvalues();
            for(double a:realEigenvalues){
                set.add(Math.round(a));
            }
        }catch (Exception e){
            set = null;
        }
        return set;
    }

    @Override
    public Double calculateDet(String str) {
        Matrix matrix = StringUtils.createMatrix(str);
        Double det = null;
        try{
            det = matrix.det();
        }catch (Exception e){}
        return det;
    }

}
